<?php

namespace app\api\controller\ec;

use app\common\controller\Api;
use app\common\exception\UploadException;
use think\Config;
use think\Hook;

/**
 * 公共接口
 * 第一步:先添加客户 到ec
 * 第二步:根据客户手机号 获取CrmId
 * 第三步：根据CrmId 获取客户信息
 */
class Ecautotuisong extends Ecbase {

    public function _initialize() {
        parent::_initialize();
    }
    
    /**
     * 废弃客户入库  while
     */
    public function tuisongFeiqiKehu(){
        
        while (true){
//            $today_start_time = strtotime("today");           
//            if((time() > $today_start_time + 18 * 3600) || (time() < $today_start_time + 8 * 3600)){
//                usleep(5000000);
//                continue;
//            }
            
            
            $controller = '\app\common\controller\zhongzhuan\Autoassigncd';
            $param = [];
            $data = call_user_func_array(array($controller, 'startAssign'),array($param));
            
            // usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
            usleep(5000000);
        }
        
    }



    /**
     * A B类客户入库
     */
    public function assignKehu(){
       
        while (true){
//            $today_start_time = strtotime("today");           
//            if((time() > $today_start_time + 18 * 3600) || (time() < $today_start_time + 8 * 3600)){
//                usleep(5000000);
//                continue;
//            }
            
            $timestamp = strtotime("today");
            $list = db('ec_assign_kehu')->where('createtime','>',$timestamp)->where('status','<>',2)->order('createtime desc')->limit(1)->select();


            foreach ($list as $key=>$value){

                if(empty($value['auto_assign']))                continue;
                //$status 0 暂停   1 分配中  2 分配完成
                $assing_kehu_detail = db('ec_assign_kehu_detail')->field('SUM(people - success_people) daifenpei,user_id')->where('assign_id',$value['id'])->where('assign_status',1)->select();

                $kehu_list = array();
                $daifenpei = 0;
                foreach ($assing_kehu_detail as $k =>$v){
                    if(empty($v['daifenpei']))                    continue;
                    $daifenpei = $v['daifenpei'] + $daifenpei;
                }
                if(empty($daifenpei)) continue;

                $limit = $daifenpei > 500 ? 500 :$daifenpei;

                $kehu_list= db('ec_ai_task_phone')->field('id byid,callJobId,customerTelephone,customerName,callInstanceId,yixiang_txt,yixiang_value,startTime,duration')->where([
                    'yixiang_value'=>['in',['A','B']],
//                    'createtime'=>['>',$timestamp],
                    'startTime'=>['>',$timestamp * 1000],
                    'status'=>0
                ])->limit($limit)->order('startTime desc')->select();



                foreach ($kehu_list as $kehu_info){                    
                    $controller = '\app\common\controller\zhongzhuan\Autoassign';
                    $param = ['assign_id'=>$value['id'],'kehu_info'=>$kehu_info];
                    $data = call_user_func_array(array($controller, 'startAssign'),array($param));    

                    usleep(1000000);
                }

            }
            
            // usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
            usleep(5000000);
        }
        
               
    }

    
    /** 
     * 推送客户 
     */
    public function addCustomer(){
        while (true){
            $list = db('ec_aiuser_to_ecuser')->limit(50)->where(['status'=>0])->select();
        
            if(empty($list)){
                usleep(5000000);
                continue;
            }
            $end_list =  [];
            $org_kehu_list = [];
            foreach ($list as $value){
                $content = json_decode($value['content'],true);
                $end_list[] = $content;
                $org_kehu_list[] = [
                    'id'=>$value['id'],
                    'mobile'=>$value['mobile']
                ];
            }
            $param = [
                'kehu_list' => $end_list,
                'opt_userid'=>$this->optUserId,
                'org_kehu_list'=>$org_kehu_list,
            ] ;

            $controller = '\app\common\controller\zhongzhuan\Fenpei';
            $data = call_user_func_array(array($controller, 'addCustomer'), array($param));
            
//            usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
//            usleep(5000000);
        }
        
        
        
        
    }
    
    
    /**
     * 更新客户标签  while  最大 200
     */
    public function ownUpdateKehuLabel(){
        
        while (true){
            
            $yixiang_label_config = [
                'A'=>'84726558','B'=>'84736557','C'=>'84734554','D'=>'84732560','E'=>'84728556','F'=>'84732561'
            ];

            $label_config = [
                '84731318', //客户来源 【新增百应】
            ];

            $list = db('ec_aiuser_to_ecuser')->where(['label_laiyuan_biaoji_status'=>0,'ecid'=>['>',0]])->where('crmId','<>','')->limit(200)->select();
            
            if(empty($list)){
                usleep(5000000);
                continue;
            }
            
            
            $end_list = $item_kehu_ids = $crmIds = [];
            foreach ($list as $value){
                $crmIds[] = $value['crmId'];
                $item_kehu_ids[] = $value['id'];
            }
            
            $param = ['crmIds' => implode(',', $crmIds),'optUserId'=>$this->optUserId,'labels'=>implode(',', $label_config)] ;
            $controller = '\app\common\controller\zhongzhuan\Fenpei';
            $item_response = call_user_func_array(array($controller, 'updateKehuLabel'), array($param));

            if($item_response['code'] == 200){
                db('ec_aiuser_to_ecuser')->where('id','in',$item_kehu_ids)->setField('label_laiyuan_biaoji_status',1);
            }

            
            // usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
            usleep(5000000);
        }
        
    }
    
    
    /**
     * 批量变更跟进人 最大50
     */
    public function batchUpdateKehuOwner(){
        while(true){
            
            
            $list = db('ec_aiuser_to_ecuser')->where(['status'=>2,'ecid'=>['>',0]])->limit(50)->select();
            
            if(empty($list)){
                usleep(5000000);
                continue;
            }

            foreach ($list as $key=>$value){
                $item_crmId = $value['crmId'];
                $item_mobile = $value['mobile'];
                $controller = '\app\common\controller\zhongzhuan\Fenpei';
                $msg_prefix = '[变更跟进人]';

                $save_data = [];
                if(empty($item_crmId)){
                    $item_crmId = db('ec_kehu')->where(['mobile'=>$item_mobile])->whereNotNull('crmId')->order('id desc')->value('crmId');                    
                }


                if(empty($item_crmId)){
                    $param = ['mobile' => $item_mobile] ;
                    $item_response = call_user_func_array(array($controller, 'getKehuInfoByOptUserid'), array($param));
                    if($item_response['code'] == 200){
                        $item_data = $item_response['data']['list'][0];
                        $item_crmId = $item_data['crmId'];
                    }
                }

                if(empty($item_crmId)){
                    $save_data['tuisong_result_txt'] = $msg_prefix .  'CrmID不存在';
                }else{
                    $save_data['crmId'] = $item_crmId;
                    $content = json_decode($value['content'],true);
                    if(!empty($content['followUserId'])){
                        $param_owner = ['followUserId'=>$content['followUserId'],'crmIds'=>$item_crmId,'optUserId'=>$this->optUserId];
                        $item_update_owner = call_user_func_array(array($controller, 'updateKehuOwnwer'), array($param_owner));

                        if($item_update_owner['code'] == 200){
                            foreach ($item_update_owner['data']['list'] as $k=>$v){
                                if($v['code'] == 40003 || $v['code'] == 200){
                                    $save_data['status'] = 1;
                                }
                                $save_data['tuisong_result_txt'] = $msg_prefix . $v['msg'];
                            }

                        }else{
                            $save_data['tuisong_result_txt'] = $msg_prefix . '请求失败';
                        }
                    }else{
                        $save_data['tuisong_result_txt'] = $msg_prefix . '跟进人为空';
                    }


                }      


                db('ec_aiuser_to_ecuser')->where('id',$value['id'])->update($save_data);

            }
            
            

           
           usleep(5000000);
        }
         
    }
    

    /**
    * 放弃客户到公海
    */
    public function batchAbandonKehu(){
        while(true){
            
            
            $list = db('ec_aiuser_to_ecuser')->where(['status'=>2,'ecid'=>0])->limit(200)->select();
            if(empty($list)){
                usleep(5000000);
                continue;
            }
            
            
            $crmIds = [];
            $crmIdNoExistList = [];
            $crmIdExistUpdateList = [];
            foreach ($list as $key=>$value){
                $item_crmId = $value['crmId'];
                $item_mobile = $value['mobile'];
                $controller = '\app\common\controller\zhongzhuan\Fenpei';
                $msg_prefix = '[放弃至公海]';
                
                if(empty($item_crmId)){
                    $crmIdExistUpdateList[$value['id']] = '';
                    $item_crmId = db('ec_kehu')->where(['mobile'=>$item_mobile])->whereNotNull('crmId')->order('id desc')->value('crmId');                    
                }


                if(empty($item_crmId)){
                    $param = ['mobile' => $item_mobile] ;
                    $item_response = call_user_func_array(array($controller, 'getKehuInfoByOptUserid'), array($param));               
                    if($item_response['code'] == 200){
                        $item_data = $item_response['data']['list'][0];
                        $item_crmId = $item_data['crmId'];                   
    //                    $this->updateSignleKehu($item_data);                    
                    }
                }            
                if(empty($item_crmId)){
                    $crmIdNoExistList[] = $value['id'];
                    continue;
                }
                
                if(array_key_exists($value['id'], $crmIdExistUpdateList)){
                    $crmIdExistUpdateList[$value['id']] = $item_crmId;
                }     
                
                $crmIds[] = $item_crmId;

            }
            
            if(!empty($crmIdNoExistList)){
                $msg = $msg_prefix .  'CrmID不存在';
                db('ec_aiuser_to_ecuser')->where('id','in',$crmIdNoExistList)->setField('tuisong_result_txt',$msg);
            }
            
            if(!empty($crmIdExistUpdateList)){
                foreach ($crmIdExistUpdateList as $k =>$v){
                    db('ec_aiuser_to_ecuser')->where('id',$k)->setField('crmId',$v);
                }
            }
            
            if(empty($crmIds)) continue;
            
            
            $param_owner = ['crmIds'=>implode(',', $crmIds),'optUserId'=>$this->optUserId,'type'=>0];
            $item_update_owner = call_user_func_array(array($controller, 'abandonKehu'), array($param_owner));

//             qqq('batchAbandonKehu',$item_update_owner);
            if($item_update_owner['code'] == 200){
                foreach ($item_update_owner['data']['list'] as $k=>$v){
                    if($v['code'] == 40003 || $v['code'] == 200){
                        $save_data['status'] = 1;
                    }
                    $save_data['status_code'] = $v['code'];
                    $save_data['tuisong_result_txt'] = $msg_prefix . $v['msg'];
                    db('ec_aiuser_to_ecuser')->where([
                        'crmId'=>$v['crmId'],
                        'status'=>2
                    ])->update($save_data);
                    
                }

            }
            
            
            
        }
        
    }
    
    
    
    
    
    
    public function batchUpdateKehuInfo(){
        while(true){
            
            $batch_update_kehu_info_status = db('ec_process_status')->where('name','batch_update_kehu_info_status')->value('status');
            if(empty($batch_update_kehu_info_status)){
                echo date('Y-m-d H:i:s');
                sleep(2* 60);
                continue;
            }
            
            $zhongzhuan_config  = config('zhongzhuan');            
            $current_page  = 1;
            $pagesize = 20;
            while(true){
                $kehu_list = db('ec_kehu')->order('id asc')->limit(($current_page-1) * $pagesize,$pagesize)->select();
                if(empty($kehu_list)) break;
                $this->_deal_page_kehuinfo($kehu_list,$zhongzhuan_config);
                $current_page = $current_page + 1;
            }
            
            
            sleep( 5 * 60 );
        }
        
        
    }
    
    
    protected function _deal_page_kehuinfo($kehu_list,$zhongzhuan_config){
        $luyin_domain_prefix = $zhongzhuan_config['luyin_domain_prefix']; 

        $field_id_config = $zhongzhuan_config['field'];
        $yixiang_field_id = $field_id_config['yixiang']['fieldid'];
        $baiying_luyin_field_id = $field_id_config['baiying_luyin']['fieldid'];
        
        $zhiying_channelId= config('zhongzhuan.zhiying_channelId');
        
        $update_kehu = [];
        $list = [];
        foreach ($kehu_list as $value){
            $org_info = json_decode($value['content'],true);

            if(empty($org_info))continue;

            $by_kehu_info = db('ec_ai_task_phone')->field('customerTelephone,callInstanceId')->where('customerTelephone',$value['mobile'])->order('id desc')->find();

            if(empty($by_kehu_info)) {
                echo '1';
                continue;
            }   

            echo $value['mobile'] . "\r\n";

            $new_luyin_file = $luyin_domain_prefix .'?callInstanceId=' .$by_kehu_info['callInstanceId'];     
            if($value['luyin_md5'] == md5($new_luyin_file)){
                echo $value['mobile'] . "\r\n";
                continue;
            }


            $fields =[];

            foreach ($org_info['fieldInfos'] as $k =>$v){
                $field_keys = array_keys($v);
                foreach ($field_keys as $item_k){                                           
                    if($item_k == $baiying_luyin_field_id){  //百应录音                            
                        $fields[$item_k] = $luyin_domain_prefix .'?callInstanceId=' .$by_kehu_info['callInstanceId'];                            
                    }else{ //意向度
                        $fields[$item_k] = empty($v[$item_k])?'':$v[$item_k];
                    }

                }

            }

            $update_kehu[$value['crmId']] = ['luyin_md5'=>md5($new_luyin_file),'record_file'=>$new_luyin_file];

            $list[] = [
                "crmId"=>$value['crmId'],"optUserId"=>$this->optUserId,"name"=>$org_info['name'],"fields"=>$fields,
                 "mobile"=>$value['mobile'],"channelId"=>$zhiying_channelId
            ];


        }       


        if(empty($list)) return;

        echo date('Y-m-d H:i:s');
        $controller = '\app\common\controller\zhongzhuan\Fenpei';
        $response_data = call_user_func_array(array($controller, 'updateInfo'), array(['list'=>$list]));
        if($response_data['code'] == 200){
            foreach ($response_data['data']['successList'] as $value){
                if(array_key_exists($value, $update_kehu)){
                    $temp = $update_kehu[$value];
                    $temp['updatetime'] = time();
                    db('ec_kehu')->where("crmId",$value)->update($temp);
                }
            }
        }
    }
    
  
}
